package com.example.demo.config;

import com.example.demo.util.ConstVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            HttpSession session = request.getSession(false);
            // 检查会话和用户是否存在
            if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
                response.sendRedirect("/home.html");
                return false;
            }
        } catch (Exception e) {
            // 记录错误信息（可以使用日志记录工具）
            System.err.println("Login Interception Error: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
            return false;
        }
        return true;
    }
}
